#include "NMPreHeader.h"
#include "NMGun.h"
#include "NMGlobalData.h"
#include "NMBulletMgr.h"

static NMGun* _gGun = NULL;

NMGun* NMGun::shared()
{
	FUNCTION_ENTER();

	if (_gGun == NULL)
		_gGun = new NMGun;


	FUNCTION_LEAVE();

	return _gGun;
}

NMGun::NMGun()
:_isFire(false)
,_angle(0)
,_fireTime(0)
{
	FUNCTION_ENTER();

	_gunbase = CCSprite::spriteWithFile("gun_base.png");
	_gunbase->setAnchorPoint(gAnchorTop);
	_gunbase->setPosition(ccp(0,-5));
	addChild(_gunbase);

	_gun = CCSprite::spriteWithFile("gun1.png");
	_gun->setAnchorPoint(ccp(0.5,0.4));
	_gun->setPosition(ccp(0,30));
	addChild(_gun);

	setAnchorPoint(gAnchorBottom);
	setPosition(ccp(160,0));

	FUNCTION_LEAVE();
}

NMGun::~NMGun(void)
{
	FUNCTION_ENTER();

	FUNCTION_LEAVE();
}

void NMGun::setAngle(float angle)
{
	FUNCTION_ENTER();

	_gun->setRotation(angle);

	FUNCTION_LEAVE();
}

void NMGun::addToLayer(CCLayer* layer)
{
	FUNCTION_ENTER();

	if (getParent())
		removeFromParentAndCleanup(false);
	layer->addChild(this, layerEnemy);

	FUNCTION_LEAVE();
}

void NMGun::removeFromStage()
{
	FUNCTION_ENTER();

	if (getParent())
		removeFromParentAndCleanup(false);

	FUNCTION_LEAVE();
}

void NMGun::update(ccTime dt)
{
	FUNCTION_ENTER();

	if (_isFire)
	{
		NMGlobalData* global = NMGlobalData::shared();
		float curAngle = _gun->getRotation();
		float rate = global->getGunFireRate();

		_fireTime += dt;
		if (_fireTime > rate)
		{
			_fireTime -= rate;
			float x = 160 + sin(CC_DEGREES_TO_RADIANS(curAngle)) * 80;
			float y = 120 - 80 + cos(CC_DEGREES_TO_RADIANS(curAngle)) * 80;

			NMBulletMgr* bulletMgr = NMBulletMgr::shared();

			switch(global->getGunLevel())
			{
			case gunLevel_Normal:
				bulletMgr->addNewBullet(ccp(x,y), curAngle);
				break;
			case gunLevel_Double:
				bulletMgr->addNewBullet(ccp(x,y), curAngle - 3);
				bulletMgr->addNewBullet(ccp(x,y), curAngle + 3);
				break;
			case gunLevel_Third:
				bulletMgr->addNewBullet(ccp(x,y), curAngle);
				bulletMgr->addNewBullet(ccp(x,y), curAngle - 5);
				bulletMgr->addNewBullet(ccp(x,y), curAngle + 5);
				break;
			default:
				assert(false);
			}
		}
	}

	FUNCTION_LEAVE();
}
